<template>
  <div id="demo1">
  </div>

</template>

<script>
import WangEditor from "wangeditor"

// todo submit logic

export default {
  name: 'CustomEditor',
  props:['detail1'],
  data() {
    return {
      editor: null,
      editorData:this.detail1,
    }
  },
  emits:['sendContent'],
  methods: {
    customPaste(editor, event, callback) {
      // console.log('ClipboardEvent 粘贴事件对象', event)
      // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
      // const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
      // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）
      // 自定义插入内容
      // editor.insertText('xxx')
      // 返回 false ，阻止默认粘贴行为
      event.preventDefault()
      callback(true) // 返回值（注意，vue 事件的返回值，不能用 return）

      // 返回 true ，继续默认的粘贴行为
      // callback(true)
    },
    processImg2Base64(img) {
      if (img) {
        let reader = new FileReader()
        reader.onload = (evt) => {
          let base64 = evt.target.result

          let targetHtml =
              "<img src=".concat(base64).concat(" style=\"max-width:100%;\" contentEditable=\"true\"/>")

          this.editor.cmd.do(
              'insertHTML',
              targetHtml
          )
        }
        reader.readAsDataURL(img)
      }
    }
  },
  mounted() {
    const editor = new WangEditor('#demo1')
    setTimeout(()=>{
      // console.log(this.detail1);
      this.editorData = this.detail1
      this.editor.txt.html(this.detail1); //初始化赋值
      console.log(this.editorData);
    },0)
    /* editor configuration */
    editor.config.onchange = (newHtml) => {
      this.editorData = newHtml
      console.log(this.editorData);
      // console.log(newHtml);
      this.$emit('sendContent',newHtml)
    }
    editor.config.uploadImgShowBase64 = true
    editor.config.withCredentials = true
    editor.config.customUploadImg = (files, insert) => {
      // console.log(files[0])
      this.processImg2Base64(files[0])
      // eslint-disable-next-line no-unused-vars
      insert = (url) => {
        // 禁用默认的 insert 方法
      }
    }
    editor.create()
    this.editor = editor
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  watch: {
  }

}
</script>

<style scoped>
</style>
